const Parse = require('parse/node')
const appInfo = require('./appinfo')
const { sign } = require('./wxsign')

let notifyQueue = []

exports.wxnotify = function (req, res, next) {
  let cb = () => {}
  while ((cb = notifyQueue.shift())) {
    cb(req.params)
  }
  next()
}

exports.wxpay = function (req, res, next) {
  _wxPay({
    spbill_create_ip: req.ip,
    notify_url: 'http://120.55.49.187/wx/notify',
    openid: req.params.openid,
    out_trade_no: req.params.out_trade_no,
    total_fee: req.params.total_fee
  }).then(data => {
    res.json(data)
    // waitForNotify((notify) => {
    //   res.json(data)
    // })
  }).catch(err => {
    res.status(400).json({ error: err })
  })
}

function _wxPay (options) {
  var base = {
    appid: appInfo.AppID,
    mch_id: appInfo.mchId,
    // nonce_str: '',
    // sign: '',
    sign_type: 'HMAC-SHA256',
    body: '只要好东西-商城',
    spbill_create_ip: '',
    notify_url: '',
    trade_type: 'JSAPI',
    openid: ''
  }
  var order = {
    out_trade_no: '',
    total_fee: ''
  }
  var params = Object.assign(base, order, options)
  Object.assign(params, sign(appInfo.AppSecret, params))
  return new Promise((resolve, reject) => {
    Parse.Cloud.httpRequest({
      url: `https://api.mch.weixin.qq.com/pay/unifiedorder`,
      params
    }).then(httpResponse => {
      var data = JSON.parse(httpResponse.text)
      resolve(data)
    }).catch(err => reject(err))
  })
}

function waitForNotify (cb) {
  if (typeof cb === 'function') notifyQueue.push(cb)
}

